﻿using Application.Common.Interfaces;
using FluentValidation;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Menus.Commands.Delete;

/// <summary>
/// 校验菜单信息
/// </summary>
public class DeleteMenuCommandValidator : AbstractValidator<DeleteMenuCommand>
{
    private readonly IApplicationDbContext _context;
    public DeleteMenuCommandValidator(IApplicationDbContext context)
    {
        _context = context;

        RuleFor(x => x.MenuIds).MustAsync(MenuExistsAsync).WithMessage("非法删除！");
    }


    private async Task<bool> MenuExistsAsync(List<long> menuIds, CancellationToken cancellationToken)
    {
        var existingMenus = await _context.Menus.Where(x => menuIds.Contains(x.Id)).ToListAsync();

        if (existingMenus == null || menuIds.Count != existingMenus.Count)
        {
            return false;
        }

        // 检查是否所有传入的角色ID都在数据库中存在且数量一致
        bool allIdsMatched = existingMenus.Select(r => r.Id).All(id => menuIds.Contains(id));

        return allIdsMatched;
    }
}